<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="接口名称" prop="apiName">
        <el-input
          v-model="queryParams.apiName"
          placeholder="请输入接口名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接口状态" prop="apiStatus">
        <el-select v-model="queryParams.apiStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.nav_api_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['navigation:api:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['navigation:api:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['navigation:api:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['navigation:api:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="apiList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="接口状态" align="center" prop="apiStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.nav_api_status" :value="scope.row.apiStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="接口名称" align="center" prop="apiName" />
      <el-table-column label="接口介绍" align="center" prop="apiIntroduce">
        <template slot-scope="scope">
          <el-popover placement="top" width="300" trigger="hover">
            <div v-html="scope.row.apiIntroduce"></div>
            <el-button slot="reference" type="text">查看详情</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="请求地址" align="center" prop="apiUrl">
        <template slot-scope="scope">
          <el-popover placement="top" width="300" trigger="hover">
            <div>{{ scope.row.apiUrl }}</div>
            <el-button slot="reference" type="text">查看详情</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="请求格式" align="center" prop="apiRequestType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.nav_request_type" :value="scope.row.apiRequestType ? scope.row.apiRequestType.split(',') : []"/>
        </template>
      </el-table-column>
      <el-table-column label="返回格式" align="center" prop="apiResponseType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.nav_response_type" :value="scope.row.apiResponseType ? scope.row.apiResponseType.split(',') : []"/>
        </template>
      </el-table-column>
      <el-table-column label="请求示例" align="center" prop="apiUrlExample">
        <template slot-scope="scope">
          <el-popover placement="top" width="300" trigger="hover">
            <div>{{ scope.row.apiUrlExample }}</div>
            <el-button slot="reference" type="text">查看详情</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="返回示例" align="center" prop="apiResponseExample">
        <template slot-scope="scope">
          <el-popover placement="top" width="300" trigger="hover">
            <div v-html="scope.row.apiResponseExample"></div>
            <el-button slot="reference" type="text">查看详情</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['navigation:api:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['navigation:api:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改接口列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="接口状态" prop="apiStatus">
          <el-radio-group v-model="form.apiStatus">
            <el-radio
              v-for="dict in dict.type.nav_api_status"
              :key="dict.value"
              :label="dict.value"
              border
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="接口名称" prop="apiName">
          <el-input v-model="form.apiName" placeholder="请输入接口名称" />
        </el-form-item>
        <el-form-item label="接口介绍" required>
          <editor v-model="form.apiIntroduce" :min-height="192"/>
        </el-form-item>
        <el-form-item label="请求地址" prop="apiUrl">
          <el-input v-model="form.apiUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="请求格式" prop="apiRequestType">
          <el-checkbox-group v-model="form.apiRequestType">
            <el-checkbox
              v-for="dict in dict.type.nav_request_type"
              :key="dict.value"
              :label="dict.value">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="返回格式" prop="apiResponseType">
          <el-checkbox-group v-model="form.apiResponseType">
            <el-checkbox
              v-for="dict in dict.type.nav_response_type"
              :key="dict.value"
              :label="dict.value">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="请求示例" prop="apiUrlExample" required>
          <el-input v-model="form.apiUrlExample" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="返回示例" prop="apiResponseExample" required>
          <editor v-model="form.apiResponseExample" :min-height="192"/>
        </el-form-item>
        <el-form-item label="请求参数" required>
          <el-row class="keyword-title text-center" :gutter="15">
            <el-col :span="4">
              <el-tag>参数名称</el-tag>
            </el-col>
            <el-col :span="4">
              <el-tag>参数类型</el-tag>
            </el-col>
            <el-col :span="4">
              <el-tag>参数说明</el-tag>
            </el-col>
            <el-col :span="4">
              <el-tag>是否必填</el-tag>
            </el-col>
          </el-row>
        </el-form-item>
        <div v-for="(item, index) in form.apiRequestKeyList">
          <el-row type="flex" align="middle">
            <el-col :span="4" style="margin-left: 80px">
              <el-form-item
                :key="index"
                :prop="'apiRequestKeyList.' + index + '.requestName'"
                :rules="{required: true, message: '参数不能为空', trigger: 'blur'}"
              >
                <el-input class="keyword-input" v-model="item.requestName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item
                :key="index"
                :prop="'apiRequestKeyList.' + index + '.requestType'"
                :rules="{required: true, message: '参数不能为空', trigger: 'change'}"
              >
                <el-select class="keyword-input" v-model="item.requestType" placeholder="请选择参数类型">
                  <el-option
                    v-for="dict in dict.type.nav_data_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item
                :key="index"
                :prop="'apiRequestKeyList.' + index + '.requestText'"
                :rules="{required: true, message: '参数不能为空', trigger: 'blur'}"
              >
                <el-input class="keyword-input" v-model="item.requestText"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item
                :key="index"
                :prop="'apiRequestKeyList.' + index + '.requestRequired'"
                :rules="{required: true, message: '参数不能为空', trigger: 'change'}"
              >
                <el-select class="keyword-input" v-model="item.requestRequired" placeholder="请选择是或否">
                  <el-option
                    v-for="dict in dict.type.sys_yes_no"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item>
                <el-button style="margin-left: -80px" type="danger" icon="el-icon-delete" circle @click.prevent="removeApiRequestKey(item)"></el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-form-item label="返回参数" required>
          <el-row class="keyword-title text-center" :gutter="15" type="flex" align="middle">
            <el-col :span="4">
              <el-tag>参数名称</el-tag>
            </el-col>
            <el-col :span="4">
              <el-tag>参数类型</el-tag>
            </el-col>
            <el-col :span="4">
              <el-tag>参数说明</el-tag>
            </el-col>
          </el-row>
        </el-form-item>
        <div v-for="(item, index) in form.apiResponseKeyList">
          <el-row type="flex" align="middle">
            <el-col :span="4" style="margin-left: 80px">
              <el-form-item
                :key="index"
                :prop="'apiResponseKeyList.' + index + '.responseName'"
                :rules="{required: true, message: '参数不能为空', trigger: 'blur'}"
              >
                <el-input class="keyword-input" v-model="item.responseName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item
                :key="index"
                :prop="'apiResponseKeyList.' + index + '.responseType'"
                :rules="{required: true, message: '参数不能为空', trigger: 'change'}"
              >
                <el-select class="keyword-input" v-model="item.responseType" placeholder="请选择参数类型">
                  <el-option
                    v-for="dict in dict.type.nav_data_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item
                :key="index"
                :prop="'apiResponseKeyList.' + index + '.responseText'"
                :rules="{required: true, message: '参数不能为空', trigger: 'blur'}"
              >
                <el-input class="keyword-input" v-model="item.responseText"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item>
                <el-button style="margin-left: -80px" type="danger" icon="el-icon-delete" circle @click.prevent="removeResponseKey(item)"></el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button type="primary" plain @click="addApiRequestKey">新增请求参数</el-button>
        <el-button type="primary" plain @click="addApiResponseKey">新增返回参数</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApi, getApi, delApi, addApi, updateApi } from "@/api/navigation/api";

export default {
  name: "Api",
  dicts: ['nav_request_type','nav_response_type','sys_yes_no','nav_data_type','nav_api_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 接口列表表格数据
      apiList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        apiName: null,
        apiIntroduce: null,
        apiUrl: null,
        apiRequestType: null,
        apiResponseType: null,
        apiStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        apiStatus: [
          { required: true, message: "请选择接口状态", trigger: "change" }
        ],
        apiName: [
          { required: true, message: "接口名称不能为空", trigger: "blur" }
        ],
        apiIntroduce: [
          { required: true, message: "接口介绍不能为空", trigger: "blur" }
        ],
        apiUrl: [
          { required: true, message: "请求地址不能为空", trigger: "blur" }
        ],
        apiRequestType: [
          { required: true, message: "请求格式不能为空", trigger: "change" }
        ],
        apiResponseType: [
          { required: true, message: "返回格式不能为空", trigger: "change" }
        ],
        apiUrlExample: [
          { required: true, message: "请求示例不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询接口列表列表 */
    getList() {
      this.loading = true;
      listApi(this.queryParams).then(response => {
        this.apiList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        apiName: null,
        apiIntroduce: null,
        apiUrl: null,
        apiRequestType: [],
        apiResponseType: [],
        apiUrlExample: null,
        apiResponseExample: null,
        apiRequestKeyList: [],
        apiResponseKeyList: [],
        apiStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加接口列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getApi(id).then(response => {
        this.form = response.data;
        this.form.apiRequestType = this.form.apiRequestType.split(",");
        this.form.apiResponseType = this.form.apiResponseType.split(",");
        this.open = true;
        this.title = "修改接口列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.apiRequestType = this.form.apiRequestType.join(",");
          this.form.apiResponseType = this.form.apiResponseType.join(",");
          if (this.form.id != null) {
            updateApi(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApi(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除接口列表编号为"' + ids + '"的数据项？').then(function() {
        return delApi(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('navigation/api/export', {
        ...this.queryParams
      }, `api_${new Date().getTime()}.xlsx`)
    },
    /** 新增请求参数 */
    addApiRequestKey() {
      this.form.apiRequestKeyList.push({
        id: null,
        apiId: null,
        requestName: null,
        requestRequired: null,
        requestType: null,
        requestText: null
      });
    },
    /** 移除请求参数 */
    removeApiRequestKey(item) {
      let index = this.form.apiRequestKeyList.indexOf(item);
      if (index !== -1) {
        this.form.apiRequestKeyList.splice(index, 1);
      }
    },
    /** 新增返回参数 */
    addApiResponseKey() {
      this.form.apiResponseKeyList.push({
        id: null,
        apiId: null,
        responseName: null,
        responseType: null,
        responseText: null
      });
    },
    /** 移除返回参数 */
    removeResponseKey(item) {
      let index = this.form.apiResponseKeyList.indexOf(item);
      if (index !== -1) {
        this.form.apiResponseKeyList.splice(index, 1);
      }
    },
  }
};
</script>

<style scoped>
.keyword-input{
  margin-left: -80px;
  width: 180px;
}
.keyword-title>div{
  margin-right: 10px;
}
</style>
